package com.four.shop.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.four.shop.dao.FreightDao;
import com.four.shop.dao.ManageDao;
import com.four.shop.dao.ParameterDao;
import com.four.shop.dao.PrictureDao;
import com.four.shop.entity.Fregiht;
import com.four.shop.entity.Manage;
import com.four.shop.entity.Parameter;
import com.four.shop.entity.Pricture;
import com.four.shop.service.ManageService;
import com.four.shop.vo.ManageVo;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.R;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author:wsy
 * @Date: 2021/12/9/15:35
 */
@Service
public class ManageServiceImpl implements ManageService {

    @Autowired
    private ManageDao manageDao;

    @Autowired
    private ParameterDao parameterDao;

    @Autowired
    private FreightDao freightDao;

    @Autowired
    private PrictureDao prictureDao;

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Manage getShopById(Integer id) {
        return manageDao.showManage(id);
    }

    /**
     * 商品管理列表
     * @param map 参数
     * @return 返回分页
     */
    @Override
    public PageUtils managePageList(Map<String, Object> map) {
        //page  当前页
        Integer page = Integer.valueOf((String) map.get("page")==null?"1":(String) map.get("page"));
        //limit  每页多少条
        Integer limit = Integer.valueOf((String) map.get("limit")==null?"3":(String) map.get("limit"));
        //商品名称模糊查
        String name = (String) map.get("name");
        //商品状态分类
        Integer state = Integer.valueOf((String) map.get("state")==null?"0":(String) map.get("state"));
        //商品分类编号
        Integer cateId = Integer.valueOf((String) map.get("cateId")==null?"0":(String) map.get("cateId"));
        //查一遍总条数
        List<Manage> list = manageDao.getList();
        //第几页第几条开始
        int size = (page-1)*limit;
        //获取分页后的列表
        List<Manage> getList = manageDao.managePageList(size, limit,name,cateId,state);
        //获取分页对象
        PageUtils pageUtils = new PageUtils(getList, list.size(), limit, page);
        return pageUtils;
    }

    /**
     * 删除编号为XXX数据
     * @param manId ：编号
     * @return ：返回状态
     */
    @Override
    public R manageDeleteById(Integer manId) {
        Integer count = manageDao.manageDeleteById(manId);
        if (count>0) {
            return R.ok();
        }
        return R.error(500,"该编号不存在");
    }

    /**
     * 添加
     * @param manage
     */
    @Override
    public void addShop(Manage manage) {
        manageDao.addShop(manage);
    }

    /**
     * 根据id上传es
     * @param id
     */
    @Override
    public void manUp(Integer id) {
        try {
            //根据id查询这条数据信息
            Manage manage = manageDao.showManage(id);
            //修改此数据的状态
            int s = 1;
            manageDao.updateManageStatus(s, id);
            IndexRequest request = new IndexRequest("manage");
            request.id(manage.getManId().toString());
            String jsonString = JSON.toJSONString(manage);
            request.source(jsonString, XContentType.JSON);
            IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据id删除es中的数据
     * @param id
     */
    @Override
    public void manDown(Integer id) {
        try {
            //根据id删除这条数据
            Manage manage = manageDao.showManage(id);
            //修改此数据的状态
            int s = 0;
            manageDao.updateManageStatus(s, id);
            DeleteRequest request = new DeleteRequest("manage", id.toString());
            DeleteResponse deleteResponse = client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @param id
     * @return
     */

    @Override
    public Manage selectMage(Integer id) {
        return manageDao.selectMage(id);
    }

    /**
     *
     * @param manage
     */

    @Override
    public void updateState(Manage manage) {
        manageDao.updateState(manage);
    }

    @Override
    public R saveManage(ManageVo manageVo, String token) {
        // 设置 Lua 脚本，其中 KEYS[1] 是 key，KEYS[2] 是 value
        String script = "if redis.call('get', KEYS[1]) == KEYS[2] then return redis.call('del', KEYS[1]) else return 0 end";
        RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
        // 根据 Key 前缀拼接 Key
        String key = "four:shop:token:" + token;
        // 执行 Lua 脚本
        Long result = redisTemplate.execute(redisScript, Arrays.asList(key, "save"));
        // 根据返回结果判断是否成功匹配并删除 Redis 键值对，若果 结果不为空和 0，则验证通过
        if (result != null && result != 0L) {
            Manage manage = new Manage();
//        商品图片
            manage.setManIcon(manageVo.getManIcon());
            //商品名称man_name
            manage.setManName(manageVo.getManName());
            //商品价格 price
            manage.setPrice(manageVo.getPrice());
            //商品销量 sales
            manage.setSales(manageVo.getSales());
            //商品库存stock
            manage.setStock(manageVo.getStock());
            //排序sort
            manage.setSort(manageVo.getSort());
            //状态(0下架,1上架)status
            manage.setStatus(manageVo.getStatus());
            //创建时间create_time
            manage.setCreateTime(manageVo.getCreateTime());
            //修改时间update_time
            manage.setUpdateTime(manageVo.getUpdateTime());
            //所属分类cat_id
            manage.setCatId(manageVo.getCatId());
            //状态分类（1出售中商品，2仓库中商品，3已经售空商品，4商品回收站）state
            manage.setState(manageVo.getState());
            //单位man_units
            manage.setManUnits(manageVo.getManUnits());
            //是否包邮（0包邮1不包邮）fre_status
            manage.setFreStatus(manageVo.getFreStatus());
            //0.单规格,1.多规格man_specs
            manage.setManSpecs(manageVo.getManSpecs());
            manageDao.addShop(manage);
            Integer id = manageDao.maxid();
            /**
             * 添加规格
             */
            if (manageVo.getManSpecs() == 0) {

                for (Parameter parameter : manageVo.getParameterList()) {
                    parameter.setManId(id);
                    parameterDao.addParameter(parameter);
                }
            } else {
                ArrayList<Parameter> parameters = new ArrayList<>();
                for (Parameter parameter : manageVo.getParameterList()) {
                    parameter.setManId(id);
                    parameters.add(parameter);
                }
                parameterDao.addParameter2(parameters);
            }
            //不包邮
            if (manageVo.getFreStatus() == 0) {
                Fregiht fregiht = new Fregiht();
                fregiht.setFreName(manageVo.getFreName());
                fregiht.setFreSatatus(manageVo.getFreSatatus());
                fregiht.setFreWeight(manageVo.getFreWeight());
                fregiht.setFrePrice(manageVo.getFrePrice());
                fregiht.setFreWeightContinue(manageVo.getFreWeightContinue());
                fregiht.setFrePriceContinue(manageVo.getFrePriceContinue());
                fregiht.setSitId(manageVo.getSitId());
                fregiht.setSitParent(manageVo.getSitParent());
                fregiht.setManId(id);
                freightDao.addFreight(fregiht);
                //包邮
            } else {
                Fregiht fregiht = new Fregiht();
                fregiht.setFreName(manageVo.getFreName());
                fregiht.setFreSatatus(manageVo.getFreSatatus());
                fregiht.setFreWeight(manageVo.getFreWeight());
                fregiht.setFrePrice(manageVo.getFrePrice());
                fregiht.setSitId(manageVo.getSitId());
                fregiht.setSitParent(manageVo.getSitParent());
                fregiht.setManId(id);
                freightDao.addFreight2(fregiht);
            }
            ArrayList<Pricture> prictures = new ArrayList<>();
            for (Pricture pricture : manageVo.getPrictures()) {
                pricture.setManId(id);
                prictures.add(pricture);
            }
            prictureDao.savePricture(prictures);
            return R.ok();
        } else {
            return R.error(500, "添加错误");
        }

    }

    @Override
    public R getToken(String value) {
        // 实例化生成 ID 工具对象
        String token = UUID.randomUUID().toString();
        // 设置存入 Redis 的 Key
        String key = "four:shop:token:" + token;
        // 存储 Token 到 Redis，且设置过期时间为 5 分钟
        redisTemplate.opsForValue().set(key, value, 5, TimeUnit.MINUTES);
        return R.ok().put("token",token);
    }

    /**
     * fegin调用所使用的查所有商品
     * @return
     */
    @Override
    public List<Manage> findAllManage() {
        return manageDao.findAllManage();
    }

    /**
     * fegin调用所使用的根据id查商品
     * @param id
     * @return
     */
    @Override
    public Manage getManageById(Integer id) {
        return manageDao.showManage(id);
    }

    @Override
    public IPage<Manage> getfindAll(Integer page, Integer pageSize, ManageVo vo) {

        Page<Manage> managePage = new Page<>(page,pageSize);

        return manageDao.getfindAll(managePage,vo);
    }
}
